import { interfaceUrl } from "@/utils/baseUrl";
import { getToken } from '@/utils/storage.js';


/**
 * 微信的request
 */
const app = getApp();

const handleResponse = (res, resolve, reject) => {
	if (res.statusCode === 200) {
			resolve(res.data);
		// 请求正常 200
		try {
			if (res.data.errors.length === 0) {
				// 正常
				resolve(res.data);
			} else if (res.data.status === 403) {
				reject("登录已过期")
				uni.showModal({
					title: '提示',
					content: '登录已过期，请立即登录，否则无法正常使用',
					success(res) {
						if (res.confirm) {
							uni.reLaunch({
								url: '/pages/login/login'
							});
							console.log('用户点击确定')
						} else if (res.cancel) {
							console.log('用户点击取消')
						}
					}
				})
			} else {
	
				uni.showToast({
					title: res.data.msg || '网络错误',
					icon: 'none',
					duration: 2000,
				});
				// 错误
				reject(res.data);
			}
		} catch (error) {
	
			reject(error)
		}
	} 
	else if(res.statusCode === 403){
		reject("登录已过期")
		uni.showModal({
			title: '提示',
			content: '登录已过期，请立即登录，否则无法正常使用',
			success(res) {
				if (res.confirm) {
					uni.reLaunch({
						url: '/pages/login/login'
					});
					console.log('用户点击确定')
				} else if (res.cancel) {
					console.log('用户点击取消')
				}
			}
		})
	}
	
	
	else {
		uni.showToast({
			title: res.data ? (res.data.msg || '') : '请求失败',
			icon: 'none',
			duration: 2000,
		});
		
		reject(res)
	}
}

export const request = function({
	url,
	data = {},
	method = "GET",
	header = {
		// 'Content-Type': method === 'POST' ? 'application/x-www-form-urlencoded' : 'application/json',
		'Content-Type': 'application/json',
	},
	timeout = 30000,
	type,
}) {

	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: method === 'GET' ? '正在加载' : '正在加载'
		});
		if (type === 'file') {
			let { file } = data;
			uni.uploadFile({
				url: url.indexOf('http') > -1 ? url : interfaceUrl + url,
				filePath: file.url,
				name: 'file',
				formData: {},
				header: {
					token: getToken() || ''
				},
				type: 'json',
				success: (res) => {
					res.data = JSON.parse(res.data);
					handleResponse(res, resolve, reject);
				},
				fail: function(err) {
					reject("服务器连接异常，请检查网络再试")
				},
				complete() {
					uni.hideLoading();
				}
			});
		} else {
			uni.request({
				url: url.indexOf('http') > -1 ? url : interfaceUrl + url,
				data: data,
				method: method,
				timeout: timeout,
				header: {
					...header,
					token: getToken() || '',
					// 'Authorization': 'Bearer ' + uni.getStorageSync('authToken') || ''
				},
				success: function(res) {
					handleResponse(res, resolve, reject);
				},
				fail: function(err) {
					reject("服务器连接异常，请检查网络再试")
				},
				complete() {
					uni.hideLoading();
				}
			})
		}
	});
}
